package com.edushare.common.util;

import java.util.ArrayList;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edushare.common.constants.ConfigPropertyName;
import com.edushare.common.exceptions.EduShareRuntimeException;
import com.edushare.common.global.SystemGlobals;
import com.edushare.common.vo.MailObject;
import com.edushare.common.vo.Users;

public class MailUtil {
	private static Log log = LogFactory.getLog(MailUtil.class);
	
	private static String HOST = SystemGlobals.getInstance().getProperties().getProperty("MAIL.HOST");
    private static String PORT = SystemGlobals.getInstance().getProperties().getProperty("MAIL.PORT");
    private static String STARTTLS = SystemGlobals.getInstance().getProperties().getProperty("MAIL.STARTTLS");
    private static String AUTH = SystemGlobals.getInstance().getProperties().getProperty("MAIL.AUTH");
    private static String USING_SSL = SystemGlobals.getInstance().getProperties().getProperty("MAIL.USING_SSL");
    private static String SOCKET_FACTORY = SystemGlobals.getInstance().getProperties().getProperty("MAIL.SOCKET_FACTORY");
    private static String SOCKET_FACTORY_PORT = SystemGlobals.getInstance().getProperties().getProperty("MAIL.SOCKET_FACTORY_PORT");
    private static String SOCKET_FACTORY_FALLBACK = SystemGlobals.getInstance().getProperties().getProperty("MAIL.SOCKET_FACTORY_FALLBACK");
    private static String DEBUG = SystemGlobals.getInstance().getProperties().getProperty("MAIL.DEBUG");
    
    public static synchronized void send(MailObject mo){
    	
    	
    	validateInput(mo);
        
    	//Use Properties object to set environment properties
        Properties props = new Properties();

        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.user", mo.getFrom());

        props.put("mail.smtp.auth", AUTH);
        props.put("mail.smtp.starttls.enable", STARTTLS);
        props.put("mail.smtp.debug", DEBUG);
        
        if(USING_SSL.equalsIgnoreCase("true")){
	        props.put("mail.smtp.socketFactory.port", SOCKET_FACTORY_PORT);
	        props.put("mail.smtp.socketFactory.class", SOCKET_FACTORY);
	        props.put("mail.smtp.socketFactory.fallback", SOCKET_FACTORY_FALLBACK);
        }
        
        try {

            //Obtain the default mail session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(true);

            //Construct the mail message
            MimeMessage message = new MimeMessage(session);
            message.setSubject(mo.getSubject());
//            message.setText(mo.getContent());
            message.setContent(mo.getContent(),"text/html");
            message.setFrom(new InternetAddress(mo.getUsername()));
            log.debug("Mail Sender User Name: "+mo.getUsername());
            log.debug("Mail Content: "+ mo.getContent());
        	
            if(mo.getTo()!=null){
            	for(String toAdd: mo.getTo()){
                	message.addRecipient(RecipientType.TO, new InternetAddress(toAdd));
                }
            }
            
            if(mo.getCc() != null){
            	for(String toAdd: mo.getCc()){
                	message.addRecipient(RecipientType.CC, new InternetAddress(toAdd));
                }
            }
            
            if(mo.getBcc() != null){
            	for(String toAdd: mo.getBcc()){
                	message.addRecipient(RecipientType.BCC, new InternetAddress(toAdd));
                }
            }
            
            message.saveChanges();

            //Use Transport to deliver the message
            Transport transport = session.getTransport("smtp");
            transport.connect(HOST, mo.getUsername(), mo.getPassword());
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

	public static void validateInput(MailObject mo) 
	throws EduShareRuntimeException{
		if(mo.getTo() == null && mo.getCc() == null && mo.getBcc() == null){
			throw new EduShareRuntimeException("No Receipient Added!");
		}
		
	}
	
	public static void sendQuickSystemMail(String to, String content){
		
		MailObject mo = new MailObject();
		mo.setContent(content);
		mo.setUsername(SystemGlobals.getInstance().getConfigProperty(ConfigPropertyName.MAIL_NOREPLY_USER));
		mo.setPassword(SystemGlobals.getInstance().getConfigProperty(ConfigPropertyName.MAIL_NOREPLY_PASSWORD));
		mo.setSubject("EduShare Registration Verification.");
		mo.setFrom("EduShare");
		ArrayList<String> toList = new ArrayList<String>();
		toList.add(to);
		mo.setTo(toList);
		MailUtil.send(mo);
	}
	
	public static String fullUserName(Users u){
		String userName = "";
		userName = (StringUtil.isValid(u.getFirstName()))?u.getFirstName():"";
		userName = userName + ((StringUtil.isValid(u.getLastName()))?" "+u.getLastName():"");
		userName = (StringUtil.isValid(userName))?userName:u.getUserName();
		userName = (StringUtil.isValid(userName))?userName.trim():"";
		return userName;
	}
}
